//
//  UserPointView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit
import MJRefresh
class UserPointView: UIView {
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var dataArray: [IntegralContentModel] = []
    override init(frame: CGRect) {
        super.init(frame: frame)
        let tableHeader = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 46))
        tableHeader.backgroundColor = .white
        self.addSubview(tableHeader)
        let ruleBtn = UIButton()
        ruleBtn.setup_titleLabel(text: MMLocalizedString("point_rules", comment: "积分规则 "))
        ruleBtn.setup_image(image: UIImage.init(named: "icon_arrow_right_black"))
        ruleBtn.semanticContentAttribute = .forceRightToLeft
        ruleBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 15)
        ruleBtn.setup_titleColor(color: Theme.titleLabColor)
        ruleBtn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 10)
        ruleBtn.addTarget(self, action: #selector(ruleBtnAction), for: .touchUpInside)
        tableHeader.addSubview(ruleBtn)
        ruleBtn.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.height.equalTo(20)
            make.bottom.equalTo(-10)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: 46, width: kScreenWidth, height: frame.size.height - 46), style: .plain)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(UserPointCell.self, forCellReuseIdentifier: "UserPointCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.whiteColor
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 128
        self.addSubview(tableView)
        
        self.setUpNoData()
        self.addPullRefreash()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.tableView.frame = self.bounds
        self.tableView.frame.origin.y = 46
        self.tableView.frame.size.height = self.bounds.size.height - 46

    }
    
    
    ///MARK: - 下拉刷新
    func addPullRefreash()  {
        weak var weakself = self
        let headerR = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself!.fetchGetDatatList()
        })
        headerR?.activityIndicatorViewStyle = .gray
        self.tableView.mj_header = headerR
        self.tableView.mj_header?.beginRefreshing()
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.tableView.ly_emptyView = self.emptyView
    }
    
    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    public func changePointItem(){
        if self.dataArray.count > 0 {
            return
        }
        self.fetchGetDatatList()
    }
    
    private func fetchGetDatatList(){
        let param: [String: String] = ["pageSize": "9999",
                                       "pageNumber":"1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberIntegralPage(param: param), objectType: IntegralResModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            let resultObj = data as! IntegralResModel
            if resultObj.code == "1" {
                self.dataArray = resultObj.data?.content ?? []
            }else{
                self.viewController().view?.makeToast(message: resultObj.msg ?? "")
            }
            self.tableView.reloadData()
        } error: { err in
            self.tableView.mj_header?.endRefreshing()
            self.viewController().view?.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///规则
    @objc func ruleBtnAction(){
        self.viewController().view?.showLoadingHUDText()
        let param:[String: String] = ["code": "POINTSRULE"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.indexPointsRule(param: param), objectType: UserRulesResModel.self) { data in
            self.viewController().view?.handleLoading()
            let resultObj = data as! UserRulesResModel
            if let tempData = resultObj.data, tempData.count > 0 {
                let vc = WebViewController()
                vc.localHtmlStr = tempData.first?.content ?? ""
                vc.titleStr = tempData.first?.title ?? ""
                self.viewController().navigationController?.pushViewController(vc, animated: true)
            }else{
                self.viewController().view?.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.viewController().view?.handleLoading()
            self.viewController().view?.makeToast(message: err?.domain ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


extension UserPointView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return IphoneXMarginBottom + 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserPointCell", for: indexPath) as! UserPointCell
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row]
            cell.setUserPointCell(data: model)
        }
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
}
